package com.cheems.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheems.springbootinit.common.ErrorCode;
import com.cheems.springbootinit.exception.BusinessException;
import com.cheems.springbootinit.mapper.CourseMapper;
import com.cheems.springbootinit.model.dto.course.CourseQueryRequest;
import com.cheems.springbootinit.model.entity.Chapter;
import com.cheems.springbootinit.model.entity.Course;
import com.cheems.springbootinit.model.entity.User;
import com.cheems.springbootinit.model.entity.UserCourse;
import com.cheems.springbootinit.model.vo.ChapterVO;
import com.cheems.springbootinit.model.vo.CourseVO;
import com.cheems.springbootinit.service.ChapterService;
import com.cheems.springbootinit.service.CourseService;
import com.cheems.springbootinit.service.UserCourseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Resource
    private UserCourseService userCourseService;
    
    @Resource
    private ChapterService chapterService;
    @Resource
    private UserServiceImpl userService;

    @Override
    public Page<Course> listCourses(CourseQueryRequest request) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        if (request != null) {
            if (StringUtils.isNotBlank(request.getTitle())) {
                queryWrapper.like("title", request.getTitle());
            }
            if (request.getTeacherId() != null) {
                queryWrapper.eq("teacher_id", request.getTeacherId());
            }
            // ... 其他查询条件
        }
        return this.page(new Page<>(request.getCurrent(), request.getPageSize()), queryWrapper);
    }
    
    @Override
    public CourseVO getCourseById(long id, HttpServletRequest request) {
        // 获取课程信息
        Course course = this.getById(id);
        if (course == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        
        // 获取课程章节信息
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", id);
        chapterQueryWrapper.orderByAsc("order_num"); // 按章节顺序排序
        List<Chapter> chapterList = chapterService.list(chapterQueryWrapper);
        
        // 转换为 VO 对象
        CourseVO courseVO = new CourseVO();
        BeanUtils.copyProperties(course, courseVO);
        
        // 转换章节列表
        List<ChapterVO> chapterVOList = chapterList.stream().map(chapter -> {
            ChapterVO chapterVO = new ChapterVO();
            BeanUtils.copyProperties(chapter, chapterVO);
            return chapterVO;
        }).collect(Collectors.toList());
        
        // 设置章节列表
        courseVO.setChapters(chapterVOList);
        
        // 如果用户已登录，查询是否已收藏和报名
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
            // 查询是否已收藏
            QueryWrapper<UserCourse> favourQueryWrapper = new QueryWrapper<>();
            favourQueryWrapper.eq("user_id", loginUser.getId());
            favourQueryWrapper.eq("course_id", id);
            favourQueryWrapper.eq("type", 0);
            courseVO.setHasFavorited(userCourseService.count(favourQueryWrapper) > 0);
            
            // 查询是否已报名
            QueryWrapper<UserCourse> enrollQueryWrapper = new QueryWrapper<>();
            enrollQueryWrapper.eq("user_id", loginUser.getId());
            enrollQueryWrapper.eq("course_id", id);
            enrollQueryWrapper.eq("type", 1);
            courseVO.setHasEnrolled(userCourseService.count(enrollQueryWrapper) > 0);
        }
        
        return courseVO;
    }
    
    @Override
    public int favoriteCourse(long courseId, User loginUser) {
        // 查询是否已收藏
        QueryWrapper<UserCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getId());
        queryWrapper.eq("course_id", courseId);
        queryWrapper.eq("type", 0);
        UserCourse userCourse = userCourseService.getOne(queryWrapper);
        
        if (userCourse != null) {
            // 取消收藏
            boolean result = userCourseService.remove(queryWrapper);
            return result ? -1 : 0;
        } else {
            // 添加收藏
            userCourse = new UserCourse();
            userCourse.setUserId(loginUser.getId());
            userCourse.setCourseId(courseId);
            userCourse.setType(0);
            boolean result = userCourseService.save(userCourse);
            return result ? 1 : 0;
        }
    }
    
    @Override
    public boolean enrollCourse(long courseId, User loginUser) {
        // 检查是否已报名
        QueryWrapper<UserCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getId());
        queryWrapper.eq("course_id", courseId);
        queryWrapper.eq("type", 1);
        if (userCourseService.count(queryWrapper) > 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "已经报名该课程");
        }
        
        // 添加报名记录
        UserCourse userCourse = new UserCourse();
        userCourse.setUserId(loginUser.getId());
        userCourse.setCourseId(courseId);
        userCourse.setType(1);
        return userCourseService.save(userCourse);
    }
} 